package com.demo.hc.interceptor;

import com.demo.hc.common.constant.WebConstant;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by whz on 2014/12/23.
 */
public class UserLoginFilter implements HandlerInterceptor {

    protected static final Logger logger = LogManager.getLogger();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String host = request.getRemoteAddr();
        logger.info("host: " + host);
        String userIdStr = (String) request.getSession().getAttribute(WebConstant.CURRENT_LOGIN_USER_ID);
        long userId = NumberUtils.toInt(userIdStr);
        if (userId > 0) {
            return true;
        } else {
            response.sendRedirect(request.getContextPath() + "/index");
            return false;
        }

    }

    private boolean isValid(String ip) {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
